<template>
  <div :key="vueRest" class="addBrand-container">
    <div :key="restKey" class="container">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" :inline="true" label-width="180px" class="demo-ruleForm">
        <div>
          <el-form-item label="账号:" prop="username">
            <el-input v-model="ruleForm.username" placeholder="请输入账号" maxlength="20" />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="员工姓名:" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入员工姓名" maxlength="15" />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="手机号:" prop="phone">
            <el-input v-model="ruleForm.phone" placeholder="请输入手机号" maxlength="20" />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="性别:" prop="sex">
            <el-radio v-model="ruleForm.sex" label="0">男</el-radio>
            <el-radio v-model="ruleForm.sex" label="1">女</el-radio>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="身份证号:" prop="idNumber">
            <el-input v-model="ruleForm.idNumber" placeholder="请输入身份证号" maxlength="20" />
          </el-form-item>
        </div>
        <div class="subBox address">
          <el-button @click="() => $router.back()">
            取消
          </el-button>
          <el-button type="primary" :class="{ continue: actionType === 'add' }" @click="submitForm('ruleForm')">
            保存
          </el-button>
          <el-button v-if="actionType == 'add'" type="primary" @click="submitForm('ruleForm', 'goAdd')">
            保存并继续添加
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
  import {
    addEmployee,
    getEmployeeById,
    updateEmployee
  } from '@/api/employee'

  import {
    Component,
    Vue,
    Watch
  } from 'vue-property-decorator'
  @Component({
    name: 'addEmployee'
  })
  export default class extends Vue {



    private actionType: string = ''

    //封装员工数据的对象
    private ruleForm = {
      username: '',
      id: '',
      name: '',
      sex: '',
      phone: '',
      idNumber: '',
      status: ''
    }
    //获取form表单的所有校验规则
    get rules() {
      return {
        username: [{
          required: true,
          validator: (rule: any, value: string, callback: Function) => {
            if (!value) {
              callback(new Error('请输入账号'))
            } else {
              const reg = /^([A-Za-z0-9\u4e00-\u9fa5]){3,20}$/
              if (!reg.test(value)) {
                callback(new Error('账号输入不符，请输入3-20个字符'))
              } else {
                callback()
              }
            }
          },
          trigger: 'blur'
        }],
        name: [{
          required: true,
          validator: (rule: any, value: string, callback: Function) => {
            if (!value) {
              callback(new Error('请输入员工姓名'))
            } else {
              const reg = /^([A-Za-z0-9\u4e00-\u9fa5]){2,20}$/
              if (!reg.test(value)) {
                callback(new Error('员工姓名输入不符，请输入2-20个字符'))
              } else {
                callback()
              }
            }
          },
          trigger: 'blur'
        }],
        phone: [{
          required: true,
          validator: (rule: any, value: string, callback: Function) => {
            if (!value) {
              callback(new Error('请输入手机号'))
            } else {
              const reg = /^1[3-9]\d{9}$/

              if (!reg.test(value)) {
                callback(new Error('手机号不符,请重新输入'))
              } else {
                callback()
              }
            }
          },
          trigger: 'blur'
        }],
        idNumber: [{
          required: true,
          validator: (rule: any, value: string, callback: Function) => {
            if (!value) {
              callback(new Error('请输入身份证号'))
            } else {
              const reg = /^\d{17}(\d|X)$/
              if (!reg.test(value)) {
                callback(new Error('身份证号不符,请重新输入'))
              } else {
                callback()
              }
            }
          },
          trigger: 'blur'
        }],

      }
    }



    created() {
      this.actionType = this.$route.query.id ? 'edit' : 'add'
      if (this.$route.query.id) {
        this.init()
      }


    }

    private async init() {
      getEmployeeById(this.$route.query.id).then(res => {
        if (res && res.data && res.data.code === 1) {
          this.ruleForm = {
            ...res.data.data
          }
        } else {
          this.$message.error(res.data.msg)
        }
      })
    }


    private submitForm(formName: any, st: any) {
      (this.$refs[formName] as any).validate((valid: any) => {
        console.log(valid, 'valid')
        if (valid) { //验证通过
          let params: any = {
            ...this.ruleForm
          }
          params.status =
            this.actionType === 'add' ? 0 : this.ruleForm.status ? 1 : 0
          if (this.actionType == 'add') { //现在是添加数据
            addEmployee(params).then(
              res => {
                if (res.data.code === 1) { //返回添加成功
                  this.$message.success('添加成功！')
                  if (!st) { //判断是否需要继续添加 否
                    this.$router.push({
                      path: '/employee'
                    })
                  } else { //是
                    this.ruleForm = {
                      username: '',
                      id: '',
                      name: '',
                      sex: '',
                      phone: '',
                      idNumber: '',
                      status: ''
                    }

                  }
                } else {
                  this.$message.error(res.data.desc || res.data.msg)
                }
              }
            ).catch(
              err => {
                this.$message.error('请求出错了：' + err.message)
              }
            )
          } else { ////现在是修改数据
            params.id = this.$route.query.id
            updateEmployee(params).then(
              res => {
                if (res.data.code === 1) { //返回添加成功
                  this.$message.success('修改成功！')
                  this.$router.push({
                    path: '/employee'
                  })

                } else {
                  this.$message.error(res.data.desc || res.data.msg)
                }
              }
            ).catch(
              err => {
                this.$message.error('请求出错了：' + err.message)
              }
            )

          }

        } else { //校验未通过
          return false
        }
      })
    }
  }

</script>

<style lang="scss" scoped>
  .addBrand {
    &-container {
      margin: 30px;
      margin-top: 30px;

      .HeadLable {
        background-color: transparent;
        margin-bottom: 0px;
        padding-left: 0px;
      }

      .container {
        position: relative;
        z-index: 1;
        background: #fff;
        padding: 30px;
        border-radius: 4px;

        // min-height: 500px;
        .subBox {
          padding-top: 30px;
          text-align: center;
          border-top: solid 1px $gray-5;
        }
      }

      .idNumber {
        margin-bottom: 39px;
      }

      .el-form-item {
        margin-bottom: 29px;
      }

      .el-input {
        width: 293px;
      }
    }
  }

</style>
